<?php

/**
 * This is the model class for table "cm_contact".
 *
 * The followings are the available columns in table 'cm_contact':
 * @property string $email
 * @property string $first_name
 * @property integer $id
 * @property string $last_name
 */
class CmContact extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return CmContact the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'cm_contact';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('email', 'required'),
			array('email, first_name, last_name', 'length', 'max'=>100),
			array('email', 'email'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('email, first_name, last_name', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'details' => array(self::HAS_ONE, 'CmDetails', 'contact_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'email' => 'E-Mail:',
			'first_name' => 'First Name:',
			'id' => 'ID',
			'last_name' => 'Last Name:',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('email',$this->email,true);
		$criteria->compare('first_name',$this->first_name,true);
//		$criteria->compare('id',$this->id);
		$criteria->compare('last_name',$this->last_name,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function getBestPhone(){
		$phone = '';
		if ($this->details) {
			switch ($this->details->best_phone) {
			case CmDetails::HOME_PHONE:
				$phone = $this->details->home_phone;
				break;
			case CmDetails::CELL_PHONE:
				$phone = $this->details->cell_phone;
				break;
			default:
				$phone = $this->details->work_phone;
				break;
			}
		}
		return $phone;
	}
	
	protected function afterDelete(){
		parent::afterDelete();
		if ($this->details) {
			$this->details->delete();
		}
	}
}